package com.taobao.mycamunda.util;

import com.taobao.mycamunda.model.ActivityNodeVO;
import org.apache.commons.lang3.ObjectUtils;
import org.camunda.bpm.engine.runtime.ActivityInstance;
import org.camunda.bpm.model.xml.instance.DomElement;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Created by zhangfei
 **/
public class ActivityNodeUtils {
    protected static ActivityNodeVO createActivityNodeByTaskElement(DomElement e){
        ActivityNodeVO activityNodeVO = new ActivityNodeVO();
        activityNodeVO.setActivityId(e.getAttribute("id"));
        activityNodeVO.setActivityName(e.getAttribute("name"));
        return activityNodeVO;
    }

    protected static Set<ActivityNodeVO> getNodeByActivityInstance(ActivityInstance activityInstance){

        if(activityInstance == null){
            return new HashSet<>();
        }

        Set<ActivityNodeVO> activityNodeVOSet = new HashSet<>();
        ActivityNodeVO activityNodeVO = new ActivityNodeVO();
        activityNodeVO.setActivityId(activityInstance.getActivityId());
        activityNodeVO.setActivityName(activityInstance.getActivityName());
        activityNodeVOSet.add(activityNodeVO);

        if(ObjectUtils.isNotEmpty(activityInstance.getChildActivityInstances())){
            for (ActivityInstance instance : activityInstance.getChildActivityInstances()){
                getNodeByActivityInstance(instance);
            }
        }

        return activityNodeVOSet;
    }

    public static List<ActivityNodeVO> createActivityNodeBySubProcessElement(DomElement e){
        List<ActivityNodeVO> activityNodeVOList = new ArrayList<>();

        e.getChildElements().stream()
                .filter(it -> "userTask".equals(it.getLocalName()) || "subProcess".equals(it.getLocalName()))
                .forEach(item ->{
                    switch (item.getLocalName()){
                        case "userTask":
                            activityNodeVOList.add(createActivityNodeByTaskElement(item));
                            break;
                        case "subProcess":
                            activityNodeVOList.addAll(createActivityNodeBySubProcessElement(item));
                            break;
                    }
                });

        return activityNodeVOList;
    }
}
